<template>
  <div style="background-color: #f5f5f5; padding: 20px; min-height: 100vh;">
    <!-- 标题部分 -->
    <div style="text-align: left; margin-bottom: 20px;">
      <i class="el-icon-s-management" style="color: #409EFF; font-size: 36px; margin-right: 10px;"></i>
      <span style="font-size: 24px; color: #333; font-weight: bold;">相册管理</span>
    </div>

    <!-- 操作区域 -->
    <div style="margin-bottom: 20px;">
      <el-button type="primary" @click="showAddAlbumDialog = true">添加相册</el-button>
    </div>

    <!-- 相册列表 -->
    <div v-if="menuItems.length" style="display: flex; flex-wrap: wrap; gap: 20px;">
      <div
          v-for="(album, index) in menuItems"
          :key="index"
          style="width: 250px; padding: 15px; background: #fff; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); border-radius: 8px; text-align: center;"
      >
        <img
            v-if="album.url"
            :src="album.url"
            alt="封面"
            style="width: 100%; height: 150px; object-fit: cover; border-radius: 8px; margin-bottom: 5px;"
            @click="onItemClick(album)"
        />
        <h3 style="font-size: 18px; color: #333; margin-bottom: 10px;">{{ album.name }}</h3>
        <p style="font-size: 12px; color: #c0c4cc;">{{ album.createTime }}</p>
        <div style="margin-top: 10px; display: flex; justify-content: center; gap: 10px;">
          <el-button size="mini" type="primary" @click="editAlbum(album)">修改</el-button>
          <el-button size="mini" type="danger" @click="del(album.id)">删除</el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div
        v-else
        style="margin-top: 20px; text-align: center; color: #bfbfbf; font-size: 18px; border: 2px dashed #dcdfe6; padding: 20px; border-radius: 4px;"
    >
      <div>
        <i class="el-icon-folder-remove" style="font-size: 48px; margin-bottom: 10px;"></i>
        <p>当前没有任何相册</p>
      </div>
    </div>

    <!-- 添加相册弹框 -->
    <el-dialog title="添加相册" :visible.sync="showAddAlbumDialog" width="700px">
      <el-form :model="newAlbum">
        <el-form-item label="相册名称" :label-width="formLabelWidth">
          <el-input v-model="newAlbum.name" placeholder="请输入相册名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="newAlbum.description" type="textarea" placeholder="请输入相册描述"></el-input>
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth">
          <el-upload
              class="cover-uploader"
              :action="$baseUrl + '/file/upload'"
              :headers="{ 'x-token': user.token }"
              :show-file-list="false"
              :on-success="handleCoverUpload"
              :before-upload="beforeCoverUpload"
          >
            <img v-if="newAlbum.cover" :src="newAlbum.cover" class="cover-preview" />
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddAlbumDialog = false">取消</el-button>
        <el-button type="primary" @click="addAlbum">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑相册弹框 -->
    <el-dialog title="编辑相册" :visible.sync="showEditAlbumDialog" width="700px">
      <el-form :model="editAlbumData">
        <el-form-item label="相册名称" :label-width="formLabelWidth">
          <el-input v-model="editAlbumData.name" placeholder="请输入相册名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="editAlbumData.descr" type="textarea" placeholder="请输入相册描述"></el-input>
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth">
          <el-upload
              class="cover-uploader"
              :action="$baseUrl + '/file/upload'"
              :headers="{ 'x-token': user.token }"
              :show-file-list="false"
              :on-success="handleEditCoverUpload"
              :before-upload="beforeCoverUpload"
          >
            <img v-if="editAlbumData.url" :src="editAlbumData.url" class="cover-preview" />
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditAlbumDialog = false">取消</el-button>
        <el-button type="primary" @click="saveEditAlbum">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "AlbumManagement",
  data() {
    return {
      user: JSON.parse(localStorage.getItem("honey-user") || "{}"), // 获取用户信息
      menuItems: [], // 相册数据列表
      showAddAlbumDialog: false, // 控制添加相册弹框
      showEditAlbumDialog: false, // 控制编辑相册弹框
      newAlbum: {
        name: "",
        description: "",
        cover: "",
      }, // 新增相册信息
      editAlbumData: {}, // 编辑相册信息
      formLabelWidth: "100px", // 表单宽度
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    onItemClick(item){
      this.$router.push({ path: '/photo', query: { id: item.id, name: item.name} });
    },
    loadData() {
      this.$request
          .post("/albums/list", { userId: this.user.userId })
          .then((res) => {
            if (res.code === "200") {
              this.menuItems = res.data;
            } else {
              this.$message.error("相册加载失败");
            }
          })
          .catch(() => {
            this.$message.error("请求失败，请检查网络连接！");
          });
    },
    addAlbum() {
      if (!this.newAlbum.name.trim()) {
        this.$message.error("相册名称不能为空");
        return;
      }
      if (!this.newAlbum.cover) {
        this.$message.error("请上传相册封面");
        return;
      }
      this.$request
          .post("/albums/add", {
            userId: this.user.userId,
            name: this.newAlbum.name,
            descr: this.newAlbum.description,
            url: this.newAlbum.cover,
          })
          .then((res) => {
            if (res.code === "200") {
              this.$message.success("相册添加成功");
              this.loadData();
              this.showAddAlbumDialog = false;
              this.newAlbum = { name: "", description: "", cover: "" };
            } else {
              this.$message.error(res.message || "相册添加失败");
            }
          })
          .catch(() => {
            this.$message.error("请求失败，请检查网络连接！");
          });
    },
    editAlbum(album) {
      this.editAlbumData = { ...album };
      this.showEditAlbumDialog = true;
    },
    saveEditAlbum() {
      this.$request
          .post("/albums/edit", { ...this.editAlbumData, userId: this.user.userId })
          .then((res) => {
            if (res.code === "200") {
              this.$message.success("相册更新成功");
              this.loadData();
              this.showEditAlbumDialog = false;
            } else {
              this.$message.error(res.message || "相册更新失败");
            }
          })
          .catch(() => {
            this.$message.error("请求失败，请检查网络连接！");
          });
    },
    del(id) {
      this.$confirm("此操作将永久删除该相册, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.$request
                .post("/albums/delete", { id: id + "" })
                .then((res) => {
                  if (res.code === "200") {
                    this.$message.success("删除成功");
                    this.menuItems = this.menuItems.filter((item) => item.id !== id);
                  } else {
                    this.$message.error(res.message || "删除失败");
                  }
                })
                .catch(() => {
                  this.$message.error("删除请求失败，请重试");
                });
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
    },
    handleCoverUpload(response) {
      if (response.code === "200") {
        this.newAlbum.cover = response.data[0].url;
        this.$message.success("封面上传成功");
      } else {
        this.$message.error(response.message || "封面上传失败");
      }
    },
    handleEditCoverUpload(response) {
      if (response.code === "200") {
        this.editAlbumData.url = response.data[0].url;
        this.$message.success("封面上传成功");
      } else {
        this.$message.error(response.message || "封面上传失败");
      }
    },
    beforeCoverUpload(file) {
      const isImage = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 20;

      if (!isImage) {
        this.$message.error("上传图片格式必须是 JPG 或 PNG!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 20MB!");
      }

      return isImage && isLt2M;
    },
  },
};
</script>

<style scoped>
/* 封面上传组件样式 */
.cover-uploader {
  width: 200px; /* 增大封面上传区域宽度 */
  height: 200px; /* 增大封面上传区域高度 */
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.cover-uploader-icon {
  font-size: 36px; /* 调整图标大小 */
  color: #8c939d;
}
</style>
